import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import RecipeDetail from '../views/RecipeDetail.vue'
import WeeklyPlan from '../views/WeeklyPlan.vue'
import CreateRecipe from '../views/CreateRecipe.vue'
import EditRecipe from '../views/EditRecipe.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import UserProfile from '../views/UserProfile.vue'
import AllRecipes from '../views/AllRecipes.vue'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory("/cook/"), // 修改路由基础路径
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/recipe/:id',
      name: 'recipe-detail',
      component: RecipeDetail,
      meta: { requiresAuth: true }
    },
    {
      path: '/recipe/:id/edit',
      name: 'edit-recipe',
      component: EditRecipe,
      meta: { requiresAuth: true }
    },
    {
      path: '/weekly-plan',
      name: 'weekly-plan',
      component: WeeklyPlan,
      meta: { requiresAuth: true }
    },
    {
      path: '/create-recipe',
      name: 'create-recipe',
      component: CreateRecipe,
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/register',
      name: 'register',
      component: Register
    },
    {
      path: '/profile',
      name: 'profile',
      component: UserProfile,
      meta: { requiresAuth: true }
    },
    {
      path: '/recipes',
      name: 'all-recipes',
      component: AllRecipes,
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化认证状态
  if (!userStore.isAuthenticated) {
    userStore.initializeAuth()
  }
  
  // 如果需要认证且未登录，跳转到登录页
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
    return
  }

  // 如果已登录且没有家庭ID，除了 profile 页面外，都跳转到 profile 页面
  if (
    userStore.isAuthenticated &&
    !userStore.user?.familyId &&
    to.name !== 'profile' &&
    to.name !== 'login' &&
    to.name !== 'register'
  ) {
    next('/profile')
    return
  }

  next()
})

export default router
